package org.realogic.cfm.persistence.mybatis.type;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

/**
 * MyBatis Boolean Type Handler
 * <p>
 * 将java的Boolean类型与jdbc中的BIT/CHAR之间进行转换;
 * <p>
 * true-1;false-0
 */
public class KBooleanTypeHandler extends BaseTypeHandler<Boolean> {

	@Override
	public Boolean getNullableResult(ResultSet rs, String columnName) throws SQLException {
		String value = rs.getString(columnName);
		Boolean rt = Boolean.FALSE;
		if ("true".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value) || "1".equals(value)) {
			rt = Boolean.TRUE;
		}
		return rt;
	}

	@Override
	public Boolean getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		String value = rs.getString(columnIndex);
		Boolean rt = Boolean.FALSE;
		if ("true".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value) || "1".equals(value)) {
			rt = Boolean.TRUE;
		}
		return rt;
	}

	@Override
	public Boolean getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		String value = cs.getString(columnIndex);
		Boolean rt = Boolean.FALSE;
		if ("true".equalsIgnoreCase(value) || "Y".equalsIgnoreCase(value) || "1".equals(value)) {
			rt = Boolean.TRUE;
		}
		return rt;
	}

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbcType) throws SQLException {
		if (parameter != null) {
			if (jdbcType == JdbcType.BIT) {
				int value = (parameter == true) ? 1 : 0;
				ps.setInt(i, value);
			} else if (jdbcType == JdbcType.CHAR) {
				String value = (parameter == true) ? "Y" : "N";
				ps.setString(i, value);
			} else {
				ps.setBoolean(i, parameter);
			}
		}
	}
}
